/*
navclouder.js

Gears worker.

Child Cloud generator
Sit around and wait for weighted list generation work

This requires json.js - make sure you pack them together before deploying.
*/

// Begin normal stuff
var wp = google.gears.workerPool;
var db = google.gears.factory.create('beta.database');
db.open();


wp.onmessage = function(parent_path, sid) {
  // Generate cloud of children for url
  var data = generateTagCloudData(parent_path);
  var msg = JSON.stringify([parent_path, data])
  wp.sendMessage(msg, sid);
  };


wp.onerror = function(err) {
  };


var generateTagCloudData = function(parent_path) {
  // First get all paths that have url as a parent
  var tags = {};
  var pathmap = {};
  var rs = db.execute(
      'select path from NounEvents where path like ?', [parent_path+'%']);
  while (rs.isValidRow()) {
    var path = rs.fieldByName('path');
    var sub = path.slice(parent_path.length);
    var words = sub.split('/');
    for (var i=0; i<words.length; i++) {
      var w = words[i]
      var previous = tags[w];
      if (previous) {
        tags[w] += 1;
        if (w == words.slice(-1)) pathmap[w] = path;
        }
      else {
        tags[w] = 1;
        pathmap[w] = path;
        }
      }
    rs.next();
    }
  return [tags, pathmap];
  };
